2.2 Maps
2.2.1 Using scatter traces
As shown in polygons, it is possible to create maps using plotly’s default (Cartesian) coordinate system, but plotly.js also has support for plotting scatter traces on top of either a custom geo layout or a mapbox layout. Figure ?? compares the three different layout options in a single subplot.
dat <- map_data("world", "canada") %>% group_by(group)
map1 <- plot_mapbox(dat, x = ~long, y = ~lat) %>%
add_paths(size = I(2)) %>%
add_segments(x = -100, xend = -50, y = 50, 75) %>%
layout(mapbox = list(
zoom = 0,
center = list(lat = ~median(lat), lon = ~median(long))
))
# geo() is the only object type which supports different map projections
map2 <- plot_geo(dat, x = ~long, y = ~lat) %>%
add_markers(size = I(1)) %>%
add_segments(x = -100, xend = -50, y = 50, 75) %>%
layout(geo = list(projection = list(type = "mercator")))
map3 <- plot_ly(dat, x = ~long, y = ~lat) %>%
add_paths(size = I(1)) %>%
add_segments(x = -100, xend = -50, y = 50, 75) %>%
layout(
xaxis = list(
scaleanchor = "y",
scaleratio = 1
)
)
htmltools::tagList(map1, map2, map3)2.2.2 Choropleths
In addition to scatter traces, plotly-geo objects also support a “native” choropleth api (i.e., plotly.js manages the geo-spatial coordinates). Figure 2.20 shows the population density of the U.S. via a choropleth, and also layers on markers for the state center locations, using the U.S. state data from the datasets package (R Core Team 2016). By simply providing a z attribute, plotly-geo objects will try to create a choropleth, but you’ll also need to provide locations and a locationmode.
density <- state.x77[, "Population"] / state.x77[, "Area"]
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
lakecolor = toRGB('white')
)
plot_geo() %>%
add_trace(
z = ~density, text = state.name,
locations = state.abb, locationmode = 'USA-states'
) %>%
add_markers(
x = state.center[["x"]], y = state.center[["y"]],
size = I(2), symbol = I(8), color = I("white"), hoverinfo = "none"
) %>%
layout(geo = g)
Figure 2.20: A map of U.S. population density using the state.x77 data from the datasets package.
Any of the add_*() functions found under scatter traces should work as expected on plotly-geo (initialized via plot_geo()) or plotly-mapbox (initialized via plot_mapbox()) objects. You can think of plot_geo() and plot_mapbox() as special cases (or more opinionated versions) of plot_ly(). For one, they won’t allow you to mix scatter and non-scatter traces in a single plot object, which you probably don’t want to do anyway. In order to enable Figure ??, plotly.js can’t make this restriction, but since we have subplot() in R, we can make this restriction without sacrificing flexibility.
2.2.3 Using geom_sf()
A more flexible and perhaps intuitive way to create maps is via ggplot2’s geom_sf() which makes it easy to visualize any geo-spatial object supported by the sf package (Pebesma 2018).
library(ggplot2)
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
p <- ggplot(nc) + geom_sf(aes(fill = AREA))
ggplotly(p)The most brilliant thing about sf is that it stores geo-spatial structures in a special list-column of a data frame. This allows each row to represent the real unit of observation/interest – whether be a polygon, multi-polygon, point, line, or even a collection of these features – and as a result, supports workflows that leverage tidy-data principles. This is way more intuitive compared to older workflows based on, say using ggplot2::fortify() to obtain a data structure where a row to represents particular point along a feature and having another column track which point belongs to each feature (for example).
2.2.4 Using ggmap
Since plotly has the ability to embed raster-based images, it’s also possible convert maps generated via the ggmap package (Kahle and Wickham 2013).
library(ggmap)
basemap <- get_map(maptype = "satellite", zoom = 8)
p <- ggmap(basemap) +
geom_polygon(aes(x = lon, y = lat, group = plotOrder),
data = zips, colour = "black", fill = NA) +
ggthemes::theme_map()
ggplotly(p)References
R Core Team. 2016. R: A Language and Environment for Statistical Computing. Vienna, Austria: R Foundation for Statistical Computing. https://www.R-project.org/.
Pebesma, Edzer. 2018. Sf: Simple Features for R. https://CRAN.R-project.org/package=sf.
Kahle, David, and Hadley Wickham. 2013. “Ggmap: Spatial Visualization with Ggplot2.” The R Journal 5 (1):144–61. http://journal.r-project.org/archive/2013-1/kahle-wickham.pdf.